<?php
/**
 * Created by PhpStorm.
 * Script Name: Mpqrcode.php
 * Create: 2023/1/10 16:29
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\MpQrcodeLog;
use plugin\wechat\app\service\Mp as MpService;
use plugin\wechat\app\TenantController;
use Support\Request;
use plugin\wechat\app\model\MpQrcode as QrcodeM;

class Mpqrcode extends TenantController
{
    /**
     * @var MpQrcodeLog
     */
    private MpQrcodeLog $logM;
    /**
     * @var QrcodeM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new QrcodeM();
        $this->logM = new MpQrcodeLog();
    }

    /**
     * 扫码记录
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function log(Request $request)
    {
        $mp_info = $request->mpInfo;
        $id = input('id', 0);
        $types = [0 => '普通扫码', 1 => '关注扫码'];
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere('log'),
                ['log.mp_id', '=', $mp_info['id']],
                ['qrcode_id', '=', $id]
            ];
            !empty($post_data['search_key']) && $where[] = [
                'follow.nickname', 'like', '%' . $post_data['search_key'] . '%'
            ];
            $query = $this->logM->alias('log')
                ->join($request->plugin . '_mp_follow follow', 'follow.openid=log.openid')
                ->where($where);

            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('log.id', 'desc')
                    ->field(['follow.headimgurl', 'follow.nickname', 'log.*'])
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '粉丝昵称']
        ])
            ->setDataUrl(url(__FUNCTION__, ['id' => $id]))
            ->addTableColumn(['title' => '粉丝昵称', 'field' => 'nickname',  'minWidth' => 100])
            ->addTableColumn(['title' => '粉丝头像', 'field' => 'headimgurl', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '扫码类型', 'field' => 'type', 'type' => 'enum','options' => $types, 'minWidth' => 100])
            ->addTableColumn(['title' => '扫码次数', 'field' => 'scan_num', 'minWidth' => 100])
            ->addTableColumn(['title' => '首次扫码时间', 'field' => 'create_time',  'minWidth' => 180])
            ->addTableColumn(['title' => '最后扫码时间', 'field' => 'update_time',  'minWidth' => 180]);

        return $builder->show();
    }

    /**
     * 二维码列表
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request)
    {
        $mp_info = $request->mpInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['mp_id', '=', $mp_info['id']]
            ];
            !empty($post_data['search_key']) && $where[] = [
                'keyword|title', 'like', '%' . $post_data['search_key'] . '%'
            ];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
                foreach ($list as $k => $v){
                    if($v['type'] == 0){
                        $v['expire_title'] = '永久';
                    }else{
                        $v['expire_title'] = date('Y-m-d H:i', strtotime($v['create_time']) + $v['expire']);
                    }
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
                ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '场景名称或关键词']
            ])
            ->addTopButton('addnew')
            ->addTableColumn(['title' => '二维码', 'field' => 'qrcode_url', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '场景名称', 'field' => 'title', 'minWidth' => 100])
            ->addTableColumn(['title' => '触发关键词', 'field' => 'keyword', 'minWidth' => 100])
            ->addTableColumn(['title' => '类型', 'field' => 'type', 'type' => 'enum','options' => [0 => '永久', 1 => '临时'], 'minWidth' => 100])
            ->addTableColumn(['title' => '短链接', 'field' => 'short_url', 'minWidth' => 200])
            ->addTableColumn(['title' => '到期时间', 'field' => 'expire_title', 'minWidth' => 180])
            ->addTableColumn(['title' => '扫码次数', 'field' => 'scan_num', 'minWidth' => 100])
            ->addTableColumn(['title' => '粉丝增加', 'field' => 'gz_num', 'minWidth' => 100])
            ->addTableColumn(['title' => '创建时间', 'field' => 'create_time',  'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 120, 'type' => 'toolbar'])
            ->addRightButton('edit', ['text' => '扫码记录', 'title' => '扫码记录', 'href' => url('log', ['id' => '__data_id__'])])
            ->addRightButton('delete');

        return $builder->show();
    }

    /**
     * 增加二维码
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function add(Request $request){
        $mp_info = $request->mpInfo;
        if(request()->isPost()){
            $post_data = input('post.');
            $post_data['mp_id'] = $mp_info['id'];
            $res = $this->validate($post_data,'\\plugin\\wechat\\app\\validate\\MpQrcode.add');
            if($res !== true){
                return $this->error($res, '', ['token' => token()]);
            }
            $data = [
                'mp_id' => $mp_info['id'],
                'company_id' => $mp_info['company_id'],
                'title' => $post_data['title'],
                'keyword' => $post_data['keyword'],
                'type' => $post_data['type'],
                'scene_str' => $post_data['scene_str'],
                'expire' => intval($post_data['expire'])
            ];

            if($post_data['type'] > 0){
                $res = MpService::qrcodeCreate($data['scene_str'], $data['expire']);
            }else{
                $res = MpService::qrcodeCreate($data['scene_str']);
            }
            if(is_string($res)){
                return $this->error("生成失败：" . $res, '', ['token' => token()]);
            }

            $data['url'] = $res['url'];
            $data['ticket'] = $res['ticket'];
            $data['qrcode_url'] = MpService::qrcodeGet($data['ticket']);
            if(is_string($short_url = MpService::urlShorten($data['qrcode_url']))){
                return $this->error("生成失败：" . $short_url, '', ['token' => token()]);
            }
            $data['short_url'] = $short_url['short_url'];

            return parent::savePost($request, '', $data);
        }
        $builder = new FormBuilder();
        $builder->addFormItem('title', 'text', '场景名称', '不超过25字', [], 'required maxlength=50')
            ->addFormItem('keyword', 'text', '关键词', '扫描此二维码的同时触发此关键词，不超过40字', [], 'required maxlength=40')
            ->addFormItem('scene_str', 'text', '场景值', '场景值ID（字符串形式的ID），字符串类型，长度限制为1到64', [], 'required maxlength=64')
            ->addFormItem('type', 'toggle_radio', '类型', '类型', [0 => '永久', 1 => '临时'], 'required')
            ->addFormItem('expire', 'number', '有效时间/秒', '临时二维码过期时间, 最大为30天（2592000秒）', [], 'required max=2592000 min=1')
            ->setFormData(['type' => 0]);
        return $builder->show();
    }
}